"""
File:send_mail.py
Author: anning
Date:-04-11
Connect:792910452@qq.com
Description:
"""
from threading import Thread

from flask import current_app, render_template
from flask_mail import Mail, Message


def thread_task(app,mail,msg):
    """多线程发送邮件任务"""
    with app.app_context():
        # 如果发生异常，则通过try,except,来捕获异常
        try:
            result=mail.send(msg)
        except Exception as e:
            print(result)
            print(str(e))
            return False
        else:
            print(result)
            return True


def send_mail(to,subject,filename,**kwargs):
    """
    发送邮件的封装
    ：param to: 收件人
    ：param subject: 邮件主题
    ：param filename: 邮件正文对应的html名称
    ：param kwargs:关键字参数，模板中需要的变量名
    :return :
    """
    # 获取当前app,以及当前app的状态
    app=current_app._get_current_object()
    # 并将获取的app与第三方插件绑定在一起
    mail=Mail(app)
    msg=Message(subject=subject,
                sender=app.config['MAIL_USERNAME'],
                recipients=to,
                )
    # recipients 表示要发给谁
    # msg.body='anan' 文本信息可以直接添加
    msg.html=render_template(filename+'.html',**kwargs)
    # 单线程发送邮件
    # with app.app_comtext():
    #    mail.send(msg)
    # 实例化多线程
    thread=Thread(target=thread_task,args=(app,mail,msg))
    # 启动多线程任务
    thread.start()
    return thread
